package com.neiquan.secondhand.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
 * 更新字段，返回新的实体
 * @author chenjunnan
 * @date 2016年7月28日
 *
 */
public class Entity {
	public static Object modify(Object entity , Object params) {
		Field [] fields = params.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			String fName = field.getName();
			if(!fName.equals("serialVersionUID")){
				Object fVal = getFieldValue(fName, params);
				if(fVal!=null&&!fVal.equals("")){
					setFieldValue(fName , entity , fVal);
				}
			}
			
			
		}
		return entity;
	}
	
	private static Object getFieldValue(String field,Object o) {
		Object obj = null;
		try {
			String f = field.substring(0,1).toUpperCase();
			String getField = "get" + f + field.substring(1);
			Method method = o.getClass().getMethod(getField, new Class[] {});    
	        obj = method.invoke(o, new Object[] {});
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return obj;
	}
	
	private static void setFieldValue(String field,Object o , Object val) {
		try {
			Field f = o.getClass().getDeclaredField(field);
			f.setAccessible(true);
			f.set(o, val);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
	}
	

}
